﻿using Blm.Utils.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using VisionCloud.Core.Model.Sys;
using VisionCloud.Domain.Common;
using VisionCloud.Domain.DtoModel.Sys;
using VisionCloud.Domain.Extension;
using VisionCloud.Domain.Repository.Interface.Sys;

namespace VisionCloud.Domain.Repository.Implement.Sys
{
    public class SysUserProjectRepository : BaseRepository<SysUserProject>, ISysUserProjectRepository
    {
        public async Task<ApiPageResult> GetPage(SysUserProjectCondition condition)
        {
            var query = from userPrj in Db.SysUserProject
                        join prj in Db.MsProjects on userPrj.ProjectId equals prj.ProjectId //into prjs
                        //from prj in prjs.DefaultIfEmpty()
                        join user in Db.SysUsers on userPrj.UserId equals user.YunUserGuid
                        where condition.UserId == Guid.Empty || condition.UserId == userPrj.UserId
                        where string.IsNullOrEmpty(condition.UserName) || user.Name.Contains(condition.UserName)
                        where string.IsNullOrEmpty(condition.UserCode) || condition.UserCode == user.Code
                        where string.IsNullOrEmpty(condition.ProjectName) || prj.Name.Contains(condition.ProjectName)
                        where condition.ProjectId == Guid.Empty || condition.ProjectId == userPrj.ProjectId
                        where condition.IsDeleted == null || condition.IsDeleted.Value == prj.IsDeleted
                        //orderby userPrj.LastUpdatedDate
                        orderby userPrj.ProjectId, userPrj.UserId
                        select new SysUserProjectDto
                        {
                            UserId = user.YunUserGuid,
                            UserCode = user.Code,
                            UserName = user.Name,
                            ProjectId = prj.ProjectId,
                            ProjectName = prj.Name,
                            UserProjectId = userPrj.UserProjectId,
                            //CreatedDate = userPrj.CreatedDate,
                            LastUpdatedDate = userPrj.LastUpdatedDate,
                            Details = prj.Details
                        };
            List<SysUserProjectDto> list = await query.ToPageList(condition).ConfigureAwait(false);

            var result = condition.CopyTo<ApiPageResult>();
            result.PageData = list;
            return result;
        }
    }
}